<template>
    <div
        v-show="dialogShow"
        class="overlay">
        <div class="signature-content">
            <div :class="btnsbox[orientation]">
                <div class="tip-text">{{ $st('wp-qing-zai-shang-fang-kong-bai-chu-qian-zi') }}</div>
                <div class="btns">
                    <van-button
                        class="btn"
                        @click="cancel">{{ $st('wp-qu-xiao') }}</van-button>
                    <van-button
                        class="btn"
                        @click="rewrite">{{ $st('wp-zhong-xie') }}</van-button>
                    <van-button
                        type="primary"
                        @click="submit"
                        class="btn">{{ $st('wp-ti-jiao') }}</van-button>
                </div>
            </div>
            <div :class="signature[orientation]">
                <canvas
                    id="canvas"
                    ref="signatureCanvas"
                    :width="widthObj[orientation] || 375"
                    :height="heightObj[orientation] || 667"
                ></canvas>
            </div>
            <div :class="currenttime[orientation]">{{ timestring }}</div>
        </div>
    </div>
</template>

<script>
import { selfI18n } from '@/i18n/index';
import { computed } from 'vue';
import SignaturePad from 'signature_pad';
import moment from 'moment';
import { showError, showConfirm } from '@/util/MessageDeal.js';

export default {
    props: {
        dialogShow: Boolean
    },
    emits: ['cancel', 'submit'],
    setup (props, ctx) {
        // computed
        const show = computed(() => {
            return props.dialogShow;
        });

        return {
            show
        };
    },
    data () {
        return {
            signaturePad: null,
            interval: null,
            timestring: '',
            orientation: 'portrait',
            signatureContent: {
                portrait: 'signature-content_90deg',
                landscape: 'signature-content_0deg'
            },
            signature: {
                portrait: 'signature_90deg',
                landscape: 'signature_0deg'
            },
            currenttime: {
                portrait: 'current-time_90deg',
                landscape: 'current-time_0deg'
            },
            btnsbox: {
                portrait: 'btns-box_90deg',
                landscape: 'btns-box_0deg'
            },
            screenWidth: window.innerWidth > 0 ? window.innerWidth : Window.screen.width,
            screenHeight: window.innerHeight > 0 ? window.innerHeight : Window.screen.height,
            widthObj: {
                portrait: this.screenWidth,
                landscape: this.screenHeight
            },
            heightObj: {
                portrait: this.screenHeight,
                landscape: this.screenWidth
            }
        };
    },
    watch: {
        show (newval, oldvel) {
            if (newval) {
                document.getElementsByTagName('body')[0].className = 'van-overflow-hidden';
            } else {
                document.body.removeAttribute('class', 'van-overflow-hidden');
            }
        }
    },
    mounted () {
        this.interval = setInterval(() => {
            this.timestring = moment().format('YYYY-MM-DD HH:mm:ss');
        }, 1000);
        this.orient();
        this.getWidthHeight();
        window.addEventListener('onorientationchange' in window ? 'orientationchange' : 'resize', () => {
            // 旋转后为了获取屏幕宽高使用setTimeout
            setTimeout(() => {
                this.screenWidth = window.innerWidth > 0 ? window.innerWidth : Window.screen.width;
                this.screenHeight = window.innerHeight > 0 ? window.innerHeight : Window.screen.height;
                this.orient();
                this.getWidthHeight();
                this.rewrite();
            }, 200);
        });
    },
    unmounted () {
        if (this.interval !== null) {
            clearInterval(this.interval);
        }
        document.body.removeAttribute('class', 'van-overflow-hidden');
    },
    methods: {
        // 获取canvas宽度、高度
        getWidthHeight () {
            if (this.orientation === 'portrait') {
                this.widthObj.portrait = this.screenWidth - 86;
                this.heightObj.portrait = this.screenHeight;
            }
            if (this.orientation === 'landscape') {
                this.widthObj.landscape = this.screenWidth;
                this.heightObj.landscape = this.screenHeight - 86;
            }
            this.$nextTick(() => {
                const signatureCanvas = this.$refs.signatureCanvas;
                this.signaturePad = new SignaturePad(signatureCanvas, { backgroundColor: '#FFFFFFFF' });
            });
        },
        // 判断是横屏竖屏
        orient () {
            // 竖屏
            if (window.orientation === 0 || window.orientation === 180) {
                this.orientation = 'portrait';
            // 横屏
            } else if (window.orientation === 90 || window.orientation === -90) {
                this.orientation = 'landscape';
            }
        },
        // 重写
        rewrite () {
            this.signaturePad.clear();
        },

        cancel () {
            this.rewrite();
            this.$emit('cancel');
        },

        // 将base64图片旋转90度
        rotateBase64 (data) {
            return new Promise((resolve) => {
                const imgView = new Image();
                imgView.src = data;
                const canvas = document.createElement('canvas');
                const context = canvas.getContext('2d');
                const cutCoor = { sx: 0, sy: 0, ex: 0, ey: 0 }; // 裁剪坐标
                imgView.onload = () => {
                    const imgW = imgView.width;
                    const imgH = imgView.height;
                    const size = imgH;
                    canvas.width = size * 2;
                    canvas.height = size * 2;
                    cutCoor.sx = size;
                    cutCoor.sy = size - imgW;
                    cutCoor.ex = size + imgH;
                    cutCoor.ey = size + imgW;
                    context.translate(size, size);
                    context.rotate(Math.PI / 2 * 3);
                    context.drawImage(imgView, 0, 0);
                    const imgData = context.getImageData(cutCoor.sx, cutCoor.sy, cutCoor.ex, cutCoor.ey);
                    canvas.width = imgH;
                    canvas.height = imgW;
                    context.putImageData(imgData, 0, 0);
                    resolve(canvas.toDataURL());
                };
            });
        },

        submit () {
            if (this.signaturePad.isEmpty()) {
                showError(selfI18n('wp-qing-qian-ming'));
                return;
            }
            showConfirm(selfI18n('wp-qian-ming-ti-jiao-hou-bu-neng-geng-gai-que-ding-ti-jiao-ma'), () => {
                const dataURL = this.signaturePad.toDataURL();
                const signatureCanvas = this.$refs.signatureCanvas;
                const canvasRect = signatureCanvas.getBoundingClientRect();
                const width = canvasRect.width;
                const height = canvasRect.height;
                if (width < height) {
                    this.rotateBase64(dataURL).then((data) => {
                        this.$emit('submit', data);
                    });
                } else {
                    this.$emit('submit', dataURL);
                }
            });
        }
    }
};
</script>
<style lang='scss' scoped>
.overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 20;
    background: #fff;
    .signature-content {
        width: 100%;
        height: 100%;
        position: relative;
    }
    .signature_90deg {
        width: calc(100vw - 86px);
        height: 100vh;
        position: absolute;
        left: 53px;
        z-index: 0;
        canvas {
            z-index: 0;
        }
    }
    .signature_0deg {
        width: 100vw;
        height: calc(100vh - 86px);
        position: absolute;
        top: 31px;
        z-index: 0;
        canvas {
            z-index: 0;
        }
    }
    .current-time_90deg {
        color: rgba(0, 0, 0, 0.45);
        padding-top: 15px;
        padding-left: 20px;
        transform: rotate(90deg);
        position: absolute;
        top: 49px;
        right: -56px;
        z-index: 1;
    }
    .current-time_0deg {
        color: rgba(0, 0, 0, 0.45);
        padding-top: 15px;
        padding-left: 20px;
        position: absolute;
        top: 0;
        z-index: 1;
    }

    .btns-box_90deg {
        display: flex;
        justify-content: space-between;
        border-top: 1px solid #e5e5e5;
        padding: 7px 15px;
        height: 53px;
        width: 100vh;
        box-sizing: border-box;
        transform: rotate(90deg);
        transform-origin: bottom left;
        position: absolute;
        top: -53px;
        background-color: #fff;
        z-index: 1;
        .tip-text {
            color: rgba(0, 0, 0, 0.45);
        }
        .btns {
            .btn {
                height: 40px;
                border-radius: 4px;
                margin-right: 10px;
                &:last-child {
                    margin-right: 0px;
                }
            }
        }
    }
    .btns-box_0deg {
        display: flex;
        justify-content: space-between;
        border-top: 1px solid #e5e5e5;
        padding: 7px 15px;
        height: 53px;
        width: 100vw;
        box-sizing: border-box;
        position: absolute;
        bottom: 0;
        background-color: #fff;
        z-index: 1;
        .tip-text {
            color: rgba(0, 0, 0, 0.45);
        }
        .btns {
            .btn {
                height: 40px;
                border-radius: 4px;
                margin-right: 10px;
                &:last-child {
                    margin-right: 0px;
                }
            }
        }
    }
}
</style>
